package com.gcloud.mesh.asset.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.util.Strings;
import org.jeecg.common.exception.MyBusinessException;
import org.jeecg.common.util.RedisUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gcloud.mesh.asset.dao.CloudResourceConfigDao;
import com.gcloud.mesh.asset.entity.CloudResourceConfigEntity;
import com.gcloud.mesh.dcs.utils.MyValidatorUtils;
import com.gcloud.mesh.framework.core.SpringUtil;
import com.gcloud.mesh.header.msg.asset.ImportCloudResourceConfigMsg;
import com.gcloud.mesh.header.msg.supplier.CreateSupplierMsg;
import com.gcloud.mesh.header.param.AliMigrationParam;
import com.gcloud.mesh.header.param.ClusterMigrationParam;
import com.gcloud.mesh.header.param.HuaweiMigrationParam;
import com.gcloud.mesh.sdk.GceSDK;
import com.gcloud.mesh.sdk.gce.ClusterVo;
import com.gcloud.mesh.sdk.gce.GcePageReply;
import com.gcloud.mesh.sdk.gce.ImportClusterVO;
import com.gcloud.mesh.supplier.enums.SystemType;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
@Service
public class ImportCloudResourceConfigServiceImpl {
    @Autowired
    CloudResourceConfigDao cloudResourceConfigDao;

    @Autowired
    RedisUtil redisUtil;

    public Map<String,Object> queryList(String cloudResourceId) {
        Map<String,Object> result = Maps.newHashMap();
        GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
        GcePageReply<ClusterVo> clusterVoGcePageReply = gceSDK.pageCluster(1, Integer.MAX_VALUE);
        result.put("clusters",clusterVoGcePageReply.getData());
        result.put("info",cloudResourceConfigDao.findOneByProperty("cloudResourceId",cloudResourceId));
        return result;
    }
	
	  public String importCluster(ImportCloudResourceConfigMsg importClusterMsg) {
	        switch (SystemType.getSystemTypeByNo(importClusterMsg.getType())){
	            case K8S: {
	                return importK8s(importClusterMsg);
	            }
	            case ALI:{
	                return importAli(importClusterMsg);
	            }
	            case HUAWEI:{
	                return importHuawei(importClusterMsg);
	            }
	            default:
	                throw new MyBusinessException("国网云类型不正确");
	        }
	    }

	    private String importHuawei(ImportCloudResourceConfigMsg importClusterMsg){
	        HuaweiMigrationParam huaweiMigrationParam = importClusterMsg.getHuaweiMigrationParam();
	        if(huaweiMigrationParam==null) throw new MyBusinessException("请填写华为云虚拟机信息");
	        String datacenterId = importClusterMsg.getDatacenterId();
	        String vmid = huaweiMigrationParam.getVmId();
	        
	        CloudResourceConfigEntity entity = cloudResourceConfigDao.findOneByProperty("cloudResourceId",importClusterMsg.getCloudResourceId());
	        if(entity==null){
	            //新增
	        	entity = new CloudResourceConfigEntity();
	        	entity.setClusterId(vmid)
	        			.setType(SystemType.HUAWEI.getNo())
	                    .setDatacenterId(datacenterId)
	                    .setCloudResourceId(importClusterMsg.getCloudResourceId())
	                    .setConfig(JSONObject.toJSONString(huaweiMigrationParam));
	        	cloudResourceConfigDao.save(entity);
	        }else{
	            //更新
	        	entity.setClusterId(vmid)
	                    .setType(SystemType.HUAWEI.getNo())
	                    .setConfig(JSONObject.toJSONString(huaweiMigrationParam));
	        	cloudResourceConfigDao.update(entity);
	        }
	        return Strings.EMPTY;
	    }

	    private String importAli(ImportCloudResourceConfigMsg importClusterMsg){
	        AliMigrationParam aliMigrationParam = importClusterMsg.getAliMigrationParam();
//	        aliMigrationParam = new AliMigrationParam();
//	        aliMigrationParam.setAccessKeyId("LTAI5tD5F828pRk2S18iUXKt");
//	        aliMigrationParam.setAccessSecret("fQ8ff7lfncvQsPAVQPGQIT579djAL2");
//	        aliMigrationParam.setInstanceId("i-7xv0j6qg6j86k87eva4j");
	        if(aliMigrationParam==null) throw new MyBusinessException("请填写阿里云虚拟机信息");
	        MyValidatorUtils.validateEntity(aliMigrationParam);
	        String datacenterId = importClusterMsg.getDatacenterId();
	        String instanceId = aliMigrationParam.getInstanceId();
	        CloudResourceConfigEntity entity = cloudResourceConfigDao.findOneByProperty("cloudResourceId",importClusterMsg.getCloudResourceId());
	        if(entity==null){
	            //新增
	        	entity = new CloudResourceConfigEntity();
	        	entity.setClusterId(instanceId)
	                    .setType(SystemType.ALI.getNo())
	                    .setDatacenterId(datacenterId)
	                    .setCloudResourceId(importClusterMsg.getCloudResourceId())
	                    .setConfig(JSONObject.toJSONString(aliMigrationParam));
	        	cloudResourceConfigDao.save(entity);
	        }else{
	            //更新
	        	entity.setClusterId(instanceId)
	                    .setType(SystemType.ALI.getNo())
	                    .setConfig(JSONObject.toJSONString(aliMigrationParam));
	        	cloudResourceConfigDao.update(entity);
	        }
	        return Strings.EMPTY;
	    }


	    private String importK8s(ImportCloudResourceConfigMsg importClusterMsg){
	        ClusterMigrationParam clusterMigrationParam = importClusterMsg.getClusterMigrationParam();
	        if(clusterMigrationParam==null) throw new MyBusinessException("请填写集群信息");
	        MyValidatorUtils.validateEntity(clusterMigrationParam);
	        String clusterId = clusterMigrationParam.getClusterId();
	        String insecureCommand = "";
	        if(StringUtils.isBlank(clusterId)){
	            //接入国网
	            if(StringUtils.isBlank(clusterMigrationParam.getClusterName())) throw new MyBusinessException("集群名称不能为空");
	            ImportClusterVO cluster = getCluster(clusterMigrationParam.getClusterName());
	            insecureCommand = cluster.getInsecureCommand();
	            clusterId = cluster.getClusterId();
	        }else{
	            GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
	            ClusterVo clusterVo = gceSDK.detailCluster(clusterId);
	            if(clusterVo==null || clusterVo.getCluster()==null) throw new MyBusinessException("集群ID有误");
	            CloudResourceConfigEntity supplierEntity = cloudResourceConfigDao.findOneByProperty("clusterId", clusterId);
	            Map<String,Object> prop = Maps.newHashMap();
	            prop.put("datacenterId",importClusterMsg.getDatacenterId());
	            prop.put("type",importClusterMsg.getType());
	            CloudResourceConfigEntity srcSe = cloudResourceConfigDao.findOneByProperties(prop);
	            if(srcSe==null && supplierEntity!=null) throw new MyBusinessException("集群已被其他数据中心接入");
	            if(srcSe!=null && supplierEntity!=null && !srcSe.getClusterId().equalsIgnoreCase(clusterId)) throw new MyBusinessException("集群已被其他数据中心接入");
	            insecureCommand = clusterVo.getCluster().getInsecureCommand();
	        }
	        CreateSupplierMsg msg = new CreateSupplierMsg();
	        BeanUtils.copyProperties(clusterMigrationParam,msg);
	        List<String> config = Lists.newArrayList();
	        Map<String,String> p = Maps.newHashMap();
	        p.put("restveleroIp",clusterMigrationParam.getRestveleroIp());
	        p.put("clusterId",clusterId);
	        config.add(JSON.toJSONString(p));
	        CloudResourceConfigEntity supplier = new CloudResourceConfigEntity();
	        supplier.setDatacenterId(importClusterMsg.getDatacenterId());
	        supplier.setCloudResourceId(importClusterMsg.getCloudResourceId());
	        supplier.setInsecureCommand(insecureCommand);
	        supplier.setType(importClusterMsg.getType());
	        supplier.setClusterId(clusterId);
	        supplier.setConfig(JSON.toJSONString(p));
	        try {
	        	cloudResourceConfigDao.save(supplier);
	        }catch(Exception e) {
	        	
	        }
	        
	        return insecureCommand;
	    }

	    public ImportClusterVO getCluster(String name){
	        try {
	            GceSDK gceSDK = SpringUtil.getBean(GceSDK.class);
	            ImportClusterVO importCluster = gceSDK.importCluster(name, "1", "1", "1");
	            if(importCluster==null) throw new MyBusinessException("导入国网失败");
	            redisUtil.set(String.format("gce:cluster:%s",name),JSON.toJSON(importCluster),60*60*24);
	            return importCluster;
	        }catch(Exception e){
	            Object o = redisUtil.get(String.format("gce:cluster:%s", name));
	            if(o!=null) return JSON.toJavaObject((JSON)JSONObject.toJSON(o),ImportClusterVO.class);
	            throw new MyBusinessException("导入国网失败");
	        }
	    }
}
